package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.OrderItemMapper;
import com.jt.mapper.OrderMapper;
import com.jt.mapper.OrderShippingMapper;
import com.jt.pojo.Order;
import com.jt.pojo.OrderItem;
import com.jt.pojo.OrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements DubboOrderService{

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderShippingMapper orderShippingMapper;



    @Override
    @Transactional
    public String saveOrder(Order order) {
        String orderId = ""+order.getUserId()+System.currentTimeMillis();//stringbuffer/stringbuilder
        Date date = new Date();

        //1.实现订单入库
        order.setOrderId(orderId).setStatus(1);//未付款
        orderMapper.insert(order);
        System.out.println("订单入库成功！！");

        //2.订单物流入库
        OrderShipping orderShipping = order.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShippingMapper.insert(orderShipping);
        System.out.println("订单物流入库成功！！");

        //3.订单商品入库
        List<OrderItem> list = order.getOrderItems();
        for(OrderItem  orderItem:list){
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }
        System.out.println("订单商品入库成功！！");

        return orderId;
    }

    @Override
    public Order findOrderById(String id) {
        Order order = orderMapper.selectById(id);
        OrderShipping orderShipping = orderShippingMapper.selectById(id);
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",id);
        List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
        order.setOrderItems(orderItems).setOrderShipping(orderShipping);
        return order;
    }
}
